package com.linxianqin.springbootVue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxianqin.springbootVue.domain.constant.UserConstants;
import com.linxianqin.springbootVue.domain.convert.SysDeptConvert;
import com.linxianqin.springbootVue.domain.dto.SysDeptDTO;
import com.linxianqin.springbootVue.domain.entity.SysDept;
import com.linxianqin.springbootVue.domain.model.TreeSelect;
import com.linxianqin.springbootVue.domain.query.SysDeptQuery;
import com.linxianqin.springbootVue.manage.exception.CustomException;
import com.linxianqin.springbootVue.mapper.SysDeptMapper;
import com.linxianqin.springbootVue.service.SysDeptService;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门表 服务实现类
 * @author lxq
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    /**
     * 查询部门管理数据
     *
     * @param query 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDeptDTO> selectDeptList(SysDeptQuery query) {
        LambdaQueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>().lambda();
        if (query.getStatus()!=null){
            queryWrapper.eq(SysDept::getStatus,query.getStatus());
        }
        if (query.getDeptName()!=null){
            queryWrapper.like(SysDept::getDeptName,query.getDeptName());
        }
        if (query.getParentId()!=null){
            queryWrapper.eq(SysDept::getParentId,query.getParentId());
        }
        List<SysDept> deptList = baseMapper.selectList(queryWrapper);
        return SysDeptConvert.INSTANCE.entity2dto(deptList);
    }

    /**
     * 查询部门列表（排除节点）
     * @param deptId
     * @return
     */
    @Override
    public List<SysDeptDTO> excludeChild(Long deptId) {
        List<SysDeptDTO> deptList = selectDeptList(new SysDeptQuery());
        deptList.removeIf(d -> d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return deptList;
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param deptList 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDeptDTO> deptList) {
        List<SysDeptDTO> deptTrees = buildDeptTree(deptList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    /**
     * 校验部门名称是否唯一
     *
     * @param deptDTO 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDeptDTO deptDTO) {
        Long deptId = StringUtils.isNull(deptDTO.getDeptId()) ? -1L : deptDTO.getDeptId();
        LambdaQueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>().lambda();
        queryWrapper.eq(SysDept::getDeptName,deptDTO.getDeptName()).eq(SysDept::getParentId,deptDTO.getParentId());
        SysDept info = baseMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>().lambda();
        queryWrapper.eq(SysDept::getParentId,deptId)
        .eq(SysDept::getStatus,"0");
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>().lambda();
        queryWrapper.eq(SysDept::getParentId,deptId);
        return baseMapper.selectCount(queryWrapper)>0;
    }

    /**
     * 递归查询子部门的所有id
     * @param deptId
     * @return
     */
    @Override
    public List<Long> selectDeptListInDept(Long deptId) {
        return baseMapper.selectDeptListInDept(deptId);
    }

    @Override
    public int insertDept(SysDeptDTO deptDTO) {
        SysDept info = baseMapper.selectById(deptDTO.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("部门停用，不允许新增");
        }
        deptDTO.setAncestors(info.getAncestors() + "," + deptDTO.getParentId());
    return baseMapper.insert(SysDeptConvert.INSTANCE.dto2entity(deptDTO));
    }


    /**
     * 构建前端所需要树结构
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    private List<SysDeptDTO> buildDeptTree(List<SysDeptDTO> deptList) {
        List<SysDeptDTO> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDeptDTO dept : deptList)
        {
            tempList.add(dept.getDeptId());
        }
        for (SysDeptDTO dept : deptList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(deptList, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = deptList;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<SysDeptDTO> list, SysDeptDTO  t) {
        // 得到子节点列表
        List<SysDeptDTO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptDTO tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptDTO> list, SysDeptDTO tChild) {
        return getChildList(list, tChild).size() > 0;
    }
    /**
     * 得到子节点列表
     */
    private List<SysDeptDTO> getChildList(List<SysDeptDTO> list, SysDeptDTO t) {
        List<SysDeptDTO> tlist = new ArrayList<>();
        for (SysDeptDTO n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
